﻿using SmazSharp;
using System;
using System.IO;
using System.Text;

namespace ToExcel
{
    internal class RawLogReader : IDisposable
    {
        internal RawLogReader(string path)
        {
            stream = new FileStream(path, FileMode.Open, FileAccess.Read);
            reader = new BinaryReader(stream);
            HasData = stream.Position < stream.Length;
        }
        private FileStream stream { get; }
        private BinaryReader reader { get; }
        public void Dispose()
        {
            reader.Close();
            stream.Dispose();
        }
        internal bool HasData { get; set; }
        internal DateTime Time { get; set; }
        internal string Text { get; set; }
        internal int Count { get; set; }
        internal RawLogReader ReadNext()
        {
            if (HasData)
            {
                var timeTick = reader.ReadInt64();
                var dataLength = reader.ReadInt32();
                Time = new DateTime(timeTick);
                Text = Encoding.UTF8.GetString(Smaz.Decompress(reader.ReadBytes(dataLength)));
                HasData = stream.Position < stream.Length;
            }
            return this;
        }
        internal void MakeCount(Action<int> callback)
        {
            if (Count > 0) return;
            Count = 0;
            while (stream.Position < stream.Length)
            {
                stream.Position += 8;
                var i = reader.ReadInt32();
                stream.Position += i;
             
                Count ++;
                callback.Invoke(Count);
            }
            stream.Position = 0;
        }
    }
}
